package com.baizhi.cmfz.service.impl;


import com.baizhi.cmfz.dao.ArticleDao;
import com.baizhi.cmfz.entiy.Article;
import com.baizhi.cmfz.service.CmfzLuceneService;
import com.baizhi.cmfz.util.LuceneUtil;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;



@Controller
@RequestMapping("cmfzLucence")
public class CmfzLucenceServiceImpl implements CmfzLuceneService {

    private Logger logger= LoggerFactory.getLogger(CmfzLucenceServiceImpl.class);


    @Autowired
    private ArticleDao dao;


    //添加一个document到索引库中
    @Override
    public boolean addOneDocument(Article cmfzArticle) {

        try {
            Document document = new Document();
            IndexWriter indexWriter = LuceneUtil.getIndexWriter();
            indexWriter.addDocument(document);
            indexWriter.commit();
            indexWriter.close();

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //创建索引库
    // 参数为要创建索引的数据
     //@return 成功返回true  失败返回false
    @Override
    public boolean createIndex(List<Article> cmfzArticleList) {
        try {

            //  1.将查询出的数据放在document对象中
            List<Document> documentList = new ArrayList<>();

            for (Article article : cmfzArticleList) {
                Document document = new Document();
                document.add(new StringField("id",article.getArticleId().toString(), Field.Store.YES));
                document.add(new TextField("name",article.getArticleName(),Field.Store.YES));
                document.add(new StringField("image",article.getArticleImage(),Field.Store.YES));
                document.add(new StringField("guruId",article.getGuruId().toString(), Field.Store.YES));

                document.add(new TextField("content",article.getArticleContent(),Field.Store.YES));
                documentList.add(document);
            }
            logger.debug("CmfzLucenceServiceImpl,创建索引______");

            // 2.创建`索引写出对象indexWriter`， 将documentList数据给索引写出对象
            IndexWriter indexWriter = LuceneUtil.getIndexWriter();
            //   将documentList数据给索引写出对象
            indexWriter.addDocuments(documentList);
            indexWriter.commit();
            indexWriter.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    //重置索引库
    @Override
    public boolean resetIndex(List<Article> cmfzArticleList) {
        IndexWriter indexWriter = LuceneUtil.getIndexWriter();
        try {
            indexWriter.deleteAll();
            indexWriter.commit();
            indexWriter.close();
            List<Document> documentList = new ArrayList<>();

            for (Article article : cmfzArticleList) {
                Document document = new Document();
                document.add(new StringField("id",article.getArticleId().toString(), Field.Store.YES));
                document.add(new TextField("name",article.getArticleName(),Field.Store.YES));
                document.add(new StringField("image",article.getArticleImage(),Field.Store.YES));
                document.add(new StringField("guruId",article.getGuruId().toString(), Field.Store.YES));

                document.add(new TextField("content",article.getArticleContent(),Field.Store.YES));
                documentList.add(document);
            }
            IndexWriter indexWriter2=LuceneUtil.getIndexWriter();
            indexWriter2.addDocuments(documentList);
            indexWriter2.commit();
            indexWriter2.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean deleteAllIndex() {

        try {
            IndexWriter indexWriter = LuceneUtil.getIndexWriter();
            indexWriter.deleteAll();
            indexWriter.commit();
            indexWriter.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }


    @Override
    public boolean deleteIndexById(int articleId) {
        try {
            IndexWriter indexWriter = LuceneUtil.getIndexWriter();
            indexWriter.deleteDocuments(new Term("articleId","1"));
            indexWriter.commit();
            indexWriter.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    //使用索引库
    @Override
    public List<Article> luceneSeleteByKeyword(String keyword) {
        //1. 准备关键词
        String keywords=keyword;
        String[] fields={"name","content"};
        //关键词处理
        Query query = LuceneUtil.queryParser(keywords, fields);
        //获取IndexSearcher对象
        IndexSearcher indexSearcher = LuceneUtil.getIndexSearcher();
        ArrayList<Article> articleList = new ArrayList<>();
        try {
            TopDocs topDocs = indexSearcher.search(query, 20);
            ScoreDoc[] scoreDocs = topDocs.scoreDocs;
            //高亮规则
            SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter("<font color='red'>", "</font>");
           //处理分词结果
            QueryScorer queryScorer = new QueryScorer(query);
            //高亮器
            Highlighter highlighter = new Highlighter(simpleHTMLFormatter, queryScorer);
            for (int i = 0; i < scoreDocs.length; i++) {
                ScoreDoc scoreDoc = scoreDocs[i];
                int docId = scoreDoc.doc;
                Document document = indexSearcher.doc(docId);
                String id = document.get("id");
                String name = document.get("name");
                String image = document.get("image");
                String content = document.get("content");
                //高亮的使用
                String name1 = null;
                String content1 = null;
                try {
                    name1 = highlighter.getBestFragment(LuceneUtil.ikAnalyzer, "name", name);
                    content1 = highlighter.getBestFragment(LuceneUtil.ikAnalyzer, "content", content);
                } catch (InvalidTokenOffsetsException e) {
                    logger.debug("高亮异常，不能处理啦");
                }

                Article article = new Article();
                article.setArticleId(Integer.parseInt(id));
                //如果文本内容无关键词，标题有，也要显示文本
                if(name1 == null){
                    article.setArticleName(name);
                }else{
                    article.setArticleName(name1);
                }
                if(content1==null){
                    article.setArticleContent(content);
                }else{
                    article.setArticleContent(content1);
                }
                article.setArticleImage(image);
                articleList.add(article);
               // System.out.println(article);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return articleList;
    }
}
